package LC.question1_100;

import java.util.HashSet;

/**
 * @author lhn
 * @date 2024-09-17 13:07
 */

public class Q003 {
    public static void main(String[] args) {
        String s1 = "abcabcbb";
        System.out.println(lengthOfLongestSubstring(s1));
        String s2 = "bbbbb";
        System.out.println(lengthOfLongestSubstring(s2));
        String s3 = "pwwkew";
        System.out.println(lengthOfLongestSubstring(s3));
    }

    //  滑动窗口，求两个重复字符间的最长距离
    public static int lengthOfLongestSubstring(String s) {
        int length = s.length();
        if (length < 2) return length;
        char[] charArray = s.toCharArray();
        HashSet<Character> set = new HashSet<>();
        int maxLength = 0;
        for (int left = 0, right = 0; right < length; right++) {    // right 从左向右遍历
            char ch = charArray[right];
            while (set.contains(ch)) {
                // 左指针向右移动，直到移除掉与当前字符重复的字符
                set.remove(charArray[left]);
                left++;
            }
            set.add(ch);
            maxLength = Math.max(maxLength, right - left + 1);
        }
        return maxLength;
    }
}
